package com.golxen.framework.common.server.cross;


import com.golxen.framework.common.CommandPlugin;
import com.golxen.framework.common.ShutDownPlugin;
import com.golxen.framework.common.server.eServerType;
import com.golxen.framework.common.server.BaseServer;
import com.golxen.framework.db.DBManager;
import com.golxen.framework.manager.ManagerPlugin;
import com.golxen.framework.manager.TempMgr;
import com.golxen.framework.netty.NettyServices;
import com.golxen.framework.netty.session.cross.CrossServerHandler;
import com.golxen.utils.LogUtil;
import com.golxen.utils.YmlUtil;
import io.netty.channel.ChannelHandler;

import java.util.List;

public class CrossBaseServer extends BaseServer {


	private static CrossBaseServer crossBaseServer;

	public static CrossBaseServer getInstance() {
		if (null == crossBaseServer) {
			crossBaseServer = new CrossBaseServer();
		}
		return crossBaseServer;
	}


	public boolean start() {

		setServerType(eServerType.CROSS);

		CommandPlugin.start();

		if (!super.start()) {
			return false;
		}

		if (!DBManager.initCrossDbConfig(serverType)) {
			return false;
		}


		if (!initNetty(new CrossServerHandler(), serverType)) {
			return false;
		}

		return true;
	}


	@Override
	public List<TempMgr> getMgrList() {
		return null;
	}

	@Override
	protected boolean initNetty(ChannelHandler handler, eServerType type) {

		nettyServices = NettyServices.start(YmlUtil.getInt("netty.cross.port"), handler, "1>" + type.value);
		if (nettyServices == null) {
			return false;
		}

		return true;
	}

	public static void main() {

		crossBaseServer = CrossBaseServer.getInstance();

		if (!crossBaseServer.start()) {
			throw new RuntimeException("CrossServer start up fail");
		}

		ShutDownPlugin.registShutDownFn(() -> {
			LogUtil.CONSOLE.info("CrossServer shutdown start...");
			crossBaseServer.stop();
			LogUtil.CONSOLE.info("CrossServer shutdown end...");
		});

	}

	@Override
	public boolean stop() {
		try {
			super.stop();
			// 保存mgr数据
			for (TempMgr baseMgr : ManagerPlugin.getMgrs()) {
				baseMgr.save();
			}
		} catch (Exception e) {
			LogUtil.COMMON.error("CrossServer close error", e);
			return false;
		}

		return true;
	}


}
